package com.example.jyp_okhttp

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.*
import java.io.IOException
import java.lang.reflect.Type
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var userAdapter: UserAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        // 获取数据并加载到 RecyclerView
        fetchUserData()
    }

    private fun fetchUserData() {
        // 创建 OkHttpClient 实例
        val client = OkHttpClient()
        // 请求 URL
        val url = "https://jsonplaceholder.typicode.com/users"
        // 创建 Request 对象
        val request = Request.Builder().url(url).build()
        // 发送异步请求
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    Toast.makeText(this@MainActivity, "请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    // 获取 JSON 响应体
                    val jsonResponse = response.body?.string()
                    // 使用 GSON 解析 JSON
                    val gson = Gson()
                    val listType: Type = object : TypeToken<List<User>>() {}.type
                    val userList = gson.fromJson<List<User>>(jsonResponse, listType)
                    // 更新 UI
                    runOnUiThread {
                        userAdapter = UserAdapter(userList)
                        recyclerView.adapter = userAdapter
                    }
                } else {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "请求失败，响应码：${response.code}", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }
}